package ssm.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import ssm.pojo.*;
import ssm.service.IBookOrderService;
import ssm.service.IBookService;
import ssm.service.ITypeService;
import ssm.service.IUserService;
import ssm.utils.DateUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * @Author: lzp
 * @Date: 2020/9/30 11:03
 * @Description: 前端控制器
 */
@Controller
@RequestMapping("/app")
public class AppController {

    @Autowired
    IBookService bookService;
    @Autowired
    IUserService userService;
    @Autowired
    IBookOrderService bookOrderService;
    @Autowired
    ITypeService typeService;

    /**
     * 跳转登录
     * @return
     */
    @RequestMapping("/login")
    public String login(){
        return "comment/login";
    }

    /**
     * 跳转注册
     * @return
     */
    @RequestMapping("/register")
    public String register(){
        return "comment/register";
    }

    /**
     * 客户端主页
     * @return
     */
    @RequestMapping("/index")
    public String index() {
        return "app/index";
    }

    /**
     * 通过id查询书籍
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/findBookById")
    public String findBookById(int id, Model model) {
        Book book = bookService.findById(id);
        model.addAttribute("book", book);
        return "app/detail";
    }

    /**
     * 下单
     * @param bookId
     * @param count
     * @param endTime
     * @param request
     * @return
     */
    @RequestMapping("/addOrder")
    @ResponseBody
    public Result addOrder(int bookId, int count, String endTime, HttpServletRequest request){
        BookOrder bookOrder = new BookOrder();
        Book book = bookService.findById(bookId);
        Date endDate = DateUtils.strToUtilDate(endTime, "yyyy-MM-dd");
        Result result = new Result();
        // 扣钱
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute("user");
        if (session != null) {
            if (user != null) {
                bookOrder.setBook(book);
                bookOrder.setCount(count);
                bookOrder.setEndTime(endDate);
                bookOrder.setUser(user);
                double spend = count * book.getPrice();
                if (user.getMoney() - spend > 0) {
                    if (book.getCount() < count) {
                        result.setFlag(false);
                        result.setMsg("书籍的库存已不足！！");
                        return result;
                    }
                    // 添加订单
                    boolean flag1 = bookOrderService.add(bookOrder);
                    // 扣钱
                    user.setMoney(user.getMoney() - spend);
                    boolean flag2 = userService.update(user);
                    // 减书
                    book.setCount(book.getCount() - count);
                    boolean flag3 = bookService.update(book);
                    if (flag1 && flag2 && flag3) {
                        session.setAttribute("user", user);
                        result.setFlag(true);
                        result.setMsg("借书成功！！");
                        return result;
                    } else {
                        result.setFlag(false);
                        result.setMsg("借书失败！！请验证数据！！");
                        return result;
                    }
                } else {
                    result.setFlag(false);
                    result.setMsg("您的余额不足！！！！");
                    return result;
                }
            }
        }
        result.setFlag(false);
        result.setMsg("请登录系统后再下单！！");
        return result;
    }

    /**
     * 通过类型id查找书籍
     * @param pageInfo
     * @param model
     * @return
     */
    @RequestMapping("/findBookByTypeId")
    public String findBookByTypeId(PageInfo<Book> pageInfo,Model model){
        bookService.findByTypeId(pageInfo);
        model.addAttribute("pageInfo", pageInfo);
        return "app/type";
    }

    /**
     * 跳转分类页，并存储id
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/type")
    public String type(int id,Model model) {
        model.addAttribute("type", typeService.findById(id));
        return "app/type";
    }

    /**
     * 登录错误
      * @return
     */
    @RequestMapping("/loginErr")
    public String loginErr() {
        return "comment/login_err";
    }

    /**
     * 查询
     * @param pageInfo
     * @return
     */
    @RequestMapping("/search")
    public String search(PageInfo<Book> pageInfo,Model model){
        //设置默认分页
        if(pageInfo.getPageSize() == 0) {
            pageInfo.setPageSize(30);
        }
        //设置查询关键词
        pageInfo.setKeyWord("%"+pageInfo.getKeyWord()+"%");
        bookService.findAll(pageInfo);
        pageInfo.setKeyWord(trimBothEndsChars(pageInfo.getKeyWord(),"%"));
        model.addAttribute("pageInfo", pageInfo);
        return "app/search";
    }

    /**
     * 去除字符串首尾两端指定的字符
     * */
    public static String trimBothEndsChars(String srcStr, String splitter) {
        String regex = "^" + splitter + "*|" + splitter + "*$";
        return srcStr.replaceAll(regex, "");
    }
}
